package online.zhangwenzhe.common.trace;

import online.zhangwenzhe.common.log.LogEntity;
import online.zhangwenzhe.common.log.LogType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;

/**
 * Description
 *
 * @author zhangwenzhe
 * @since 2018/8/16 下午7:26
 */

public class TracingLogging {

    protected static final Logger logger = LoggerFactory.getLogger(TracingFilter.class);
    private static final String REQUEST_PREFIX = "Request: ";
    private static final String RESPONSE_PREFIX = "Response: ";

    public static void logRequest(final HttpServletRequest request) {
        StringBuilder msg = new StringBuilder();
        msg.append(REQUEST_PREFIX);

        HttpSession session = request.getSession(false);
        if (session != null) {
            msg.append("session id=").append(session.getId()).append("; ");
        }
        if (request.getMethod() != null) {
            msg.append("method=").append(request.getMethod()).append("; ");
        }
        if (request.getContentType() != null) {
            msg.append("content type=").append(request.getContentType()).append("; ");
        }
        msg.append("uri=").append(request.getRequestURI());
        if (request.getQueryString() != null) {
            msg.append('?').append(request.getQueryString());
        }

        if (request instanceof RequestWrapper && !isMultipart(request) && !isBinaryContent(request)) {
            RequestWrapper requestWrapper = (RequestWrapper) request;
            try {
                String charEncoding = requestWrapper.getCharacterEncoding() != null ? requestWrapper.getCharacterEncoding() :
                        "UTF-8";
                msg.append("; payload=").append(new String(requestWrapper.toByteArray(), charEncoding));
            } catch (UnsupportedEncodingException e) {
                logger.warn("Failed to parse request payload", e);
            }
        }

        long traceId = 0L;
        if (request instanceof RequestWrapper) {
            RequestWrapper requestWrapper = (RequestWrapper) request;
            traceId = requestWrapper.getId();
        }

        LogEntity logEntity = new LogEntity(traceId, LogType.HTTP_TRACE, msg.toString());

        logger.info(logEntity.toJson());
    }

    private static boolean isBinaryContent(final HttpServletRequest request) {
        if (request.getContentType() == null) {
            return false;
        }
        return request.getContentType().startsWith("image") || request.getContentType().startsWith("video") || request.getContentType().startsWith("audio");
    }

    private static boolean isMultipart(final HttpServletRequest request) {
        return request.getContentType() != null && request.getContentType().startsWith("multipart/form-data");
    }

    public static void logResponse(final ResponseWrapper response, long timeSpend) {
        StringBuilder msg = new StringBuilder();
        msg.append(RESPONSE_PREFIX);

        try {
            msg.append("state=").append(response.getStatus()).append("; ");
            msg.append("timeSpend=").append(timeSpend).append("; ");
            msg.append("payload=").append(new String(response.toByteArray(), response.getCharacterEncoding()));
        } catch (UnsupportedEncodingException e) {
            logger.warn("Failed to parse response payload", e);
        }

        long traceId = 0L;
        if (response instanceof ResponseWrapper) {
            ResponseWrapper responseWrapper = (ResponseWrapper) response;
            traceId = responseWrapper.getId();
        }

        LogEntity logEntity = new LogEntity(traceId, LogType.HTTP_TRACE, msg.toString());

        logger.info(logEntity.toJson());
    }
}
